<?php

/*
    Class   : SelectFilter ( RecursiveArrayIterator technique )
    Author  : Suwandi Tan
    
    Copyright (C) 2011  Suwandi Tan ( swndtan@gmail.com )

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


class SelectFilter extends RecursiveArrayIterator
{
    private $select = array();
    
    private $results = array();
    private $key;
    
    function select($select = array())
    {
        $this->select = $select;
    }
    
    function crawl()
    {
        $this->results = array();
        $this->key = 0;
        
        iterator_apply($this, array($this, 'recursive'), array($this));
        
        return array_merge($this->results);
    }
    
    function recursive($iterator)
    {
        while($iterator->valid())
        {
            if($iterator->hasChildren())
            {
                $this->recursive($iterator->getChildren());
                ++$this->key;
            }
            else
            {
                if(in_array($iterator->key(), $this->select)) $this->results [$this->key][$iterator->key()] = $iterator->current();
            }
            
            $iterator->next();
        }
        
    }
}


